#include "UP_test.h"
#include "gd32f4xx.h"
#include "systick.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "UP_GPIO.h"
#include "UP_USART.h"
#include "UP_DMA.h"

#define LED1 PE3
#define LED2 PD7
#define LED3 PG3
#define LED4 PA5

UP_GPIO leds[] = {LED1, LED2, LED3, LED4};

void DMA_test(void)
{
	nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2); // 优先级分组
	systick_config();

	GPIO_Init(LED1, 0);
	GPIO_Init(LED2, 0);
	GPIO_Init(LED3, 0);
	GPIO_Init(LED4, 0);

	UP_USART config;
	config.TR_mode = USART_RECEIVE_TRANSMIT_MODE;
	config.nvic_irq_pre_priority = 3;
	config.nvic_irq_sub_priority = 3;

	// 初始化USART
	USART_init_with_config(
		USART0,			// USART USARTx(x=0,1,2,5) / UARTx(x=3,4,6,7)
		115200U,		// 波特率
		USART_WL_8BIT,	// 数据位
		USART_STB_1BIT, // 停止位
		USART_PM_NONE,	// 校验位
		config);

	printf("----------------------------usart dma test \r\n");

	// DMA通道：  0->7 根据用户手册中10.4.1外设握手的外设请求表，不同的协议确定
	uint8_t channel = 2;			  //USART0_RX的PERIEN通道
	// 外设通道： 0->7 根据用户手册中10.4.1外设握手的外设请求表，不同的协议通道的二进制确定
	uint8_t subperipheral_select = 4; //USART0_RX的通道
	// 初始化DMA
	DMA_init(DMA1, channel, subperipheral_select);

	while (1)
	{
	}
}

void on_dma_data_received(uint32_t usartx, char *data, uint16_t length)
{


	printf("length:%d ", length); // 打印接收的数据长度
	printf("dma_data:%s\r\n", data);	// 打印接收的数据

	if (strncmp(data, "led", 3) == 0)
	{
		// 根据接收到的ledx on/off信号控制指定灯亮灭

		char *cmd = strtok(data, " ");
		char *arg = strtok(NULL, " ");
		int led_num = atoi(&cmd[3]);

		printf("cmd: %s\n", cmd);
		printf("arg: %s\n", arg);
		printf("led_num: %d\n", led_num);

		if (led_num > 0 && led_num <= 4)
		{
			if (strcmp(arg, "on") == 0)
			{
				GPIO_Set(leds[led_num - 1], 1);
			}
			else if (strcmp(arg, "off") == 0)
			{
				GPIO_Set(leds[led_num - 1], 0);
			}
		}
	}
}
